import Vue from 'vue';
import VueApollo from 'vue-apollo';
import { GlButton, GlModal } from '@gitlab/ui';
import { createMockSubscription } from 'mock-apollo-client';
import createMockApollo from 'helpers/mock_apollo_helper';
import { mountExtended } from 'helpers/vue_test_utils_helper';
import AiCommitMessage from 'ee/vue_merge_request_widget/components/ai_commit_message.vue';
import waitForPromises from 'helpers/wait_for_promises';
import aiCommitMessageMutation from 'ee/vue_merge_request_widget/queries/ai_commit_message.mutation.graphql';
import aiResponseSubscription from 'ee/graphql_shared/subscriptions/ai_completion_response.subscription.graphql';

Vue.use(VueApollo);

describe('Ai Commit Message component', () => {
  let wrapper;
  let aiResponseSubscriptionHandler;
  let aiCommitMessageMutationHandler;
  const userId = 99;

  const createComponent = () => {
    window.gon = { current_user_id: userId };

    aiResponseSubscriptionHandler = createMockSubscription();
    aiCommitMessageMutationHandler = jest
      .fn()
      .mockResolvedValue({ data: { aiAction: { errors: [], __typename: 'AiActionPayload' } } });
    const mockApollo = createMockApollo([
      [aiCommitMessageMutation, aiCommitMessageMutationHandler],
    ]);
    mockApollo.defaultClient.setRequestHandler(
      aiResponseSubscription,
      () => aiResponseSubscriptionHandler,
    );

    wrapper = mountExtended(AiCommitMessage, {
      apolloProvider: mockApollo,
      propsData: {
        id: 1,
      },
    });
  };

  it('triggers AI mutation', async () => {
    createComponent();

    wrapper.findComponent(GlButton).vm.$emit('click');

    await waitForPromises();

    expect(aiCommitMessageMutationHandler).toHaveBeenCalledWith({
      resourceId: 'gid://gitlab/MergeRequest/1',
    });
  });

  it('emits update event when user clicks insert', async () => {
    createComponent();
    aiResponseSubscriptionHandler.next({
      data: {
        aiCompletionResponse: {
          responseBody: 'commit message',
          errors: [],
        },
      },
    });

    await waitForPromises();

    wrapper.findComponent(GlModal).vm.$emit('primary');

    expect(wrapper.emitted('update')).toEqual([
      ['commit message\n\n-------\n:robot: Commit message generated by AI'],
    ]);
  });
});
